import * as types from '../mutation-types'
import {getTopic, uped} from 'api/topics'
import moment from 'moment'

moment.locale('zh-cn')

const state = {
  topicDetail: {}
}

// getters
const getters = {
  topicDetail: state => state.topicDetail
}

// actions
const actions = {
  TopicDetail({commit}, {id, token}) {
    return getTopic(id, token).then((res) => {
      if (res.success === false) {
        return res
      } else {
        res.data.create_at = moment(res.data.create_at).startOf().fromNow()
        res.data.last_reply_at = moment(res.data.last_reply_at).startOf().fromNow()
        commit(types.SET_TOPIC_DETAIL, res.data)
        return res
      }
    })
  },
  checkUp({commit}, {id, token}) {
    return uped(id, token).then((res) => {
      if (res.success === false) {
        return res
      } else {
        let topicDetail = {}
        topicDetail = JSON.parse(JSON.stringify(state.topicDetail))
        let replies = topicDetail.replies.slice()
        let currentIndex = 0
        replies.forEach((value, index) => {
          if (value.id === id) {
            currentIndex = index
          }
        })
        if (res.action === 'up') {
          replies[currentIndex].is_uped = true
          replies[currentIndex].ups.length++
        } else {
          replies[currentIndex].is_uped = false
          replies[currentIndex].ups.length--
        }
        topicDetail.replies = replies
        commit(types.SET_TOPIC_DETAIL, topicDetail)
        return res
      }
    })
  }
}

// mutations
const mutations = {
  [types.SET_TOPIC_DETAIL](state, val) {
    state.topicDetail = val
  }
}

export default {
  state,
  getters,
  actions,
  mutations
}
